package com.legendframework.core.dao.utils;

import com.legendframework.core.support.lang3.StringUtils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DaoStringUtils extends StringUtils {

    /**
     * 下划线转驼峰正则表达式
     */
    private static Pattern linePattern = Pattern.compile("_(\\w)");


    /**
     * 驼峰转下划线正则表达式
     */
    private static Pattern humpPattern = Pattern.compile("[A-Z]");

    /**
     * 空字符
     */
    public static final String EMPTY = "";

    /**
     * 字符串 is
     */
    public static final String IS = "is";

    /**
     * 解析 getMethodName -> propertyName
     *
     * @param getMethodName 需要解析的
     * @return 返回解析后的字段名称
     */
    public static String resolveFieldName(String getMethodName) {
        if (getMethodName.startsWith("get")) {
            getMethodName = getMethodName.substring(3);
        } else if (getMethodName.startsWith(IS)) {
            getMethodName = getMethodName.substring(2);
        }
        // 小写第一个字母
        return DaoStringUtils.firstToLowerCase(getMethodName);
    }

    /**
     * 首字母转换小写
     *
     * @param param 需要转换的字符串
     * @return 转换好的字符串
     */
    public static String firstToLowerCase(String param) {
        if (isEmpty(param)) {
            return EMPTY;
        }
        return param.substring(0, 1).toLowerCase() + param.substring(1);
    }

    /**
     * 首字母转大写
     * @param str
     * @return
     */
    private static String getConvert(String str) {
        String first = str.substring(0, 1);
        String after = str.substring(1);
        first = first.toUpperCase();
        return first + after;
    }

    /**
     * 将属性名转为set方法名
     * @param fieldName
     * @return
     */
    public static String fieldNameToSetterMethodName(String fieldName){
        return "set"+getConvert(fieldName);
    }

    /**
     * 将属性名转为get方法名
     * @param fieldName
     * @return
     */
    public static String fieldNameToGetterMethodName(String fieldName){
        return "get"+getConvert(fieldName);
    }

    /**
     * 下划线转驼峰
     * @param str
     * @return
     */
    public static String lineToHump(String str) {
        str = str.toLowerCase();
        Matcher matcher = linePattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
        }
        matcher.appendTail(sb);
        return sb.toString();
    }


    /**
     * 驼峰转下划线
     * @param str
     * @return
     */
    public static String humpToLine(String str) {
        Matcher matcher = humpPattern.matcher(str);
        StringBuffer sb = new StringBuffer();
        while (matcher.find()) {
            matcher.appendReplacement(sb, "_" + matcher.group(0).toLowerCase());
        }
        matcher.appendTail(sb);
        if (sb.toString().startsWith("_")) {
            return sb.toString().substring(1);
        }
        return sb.toString();
    }

}
